import axios from 'axios'
import { Toast } from 'vant'
import config from '@/config'
import store from '@/store/index.js'

// 创建axios实例
const instance = axios.create({
  baseURL: config.VITE_API_BASE_URL,
  timeout: 300000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
// 异常拦截处理器
const errorHandler = (error) => {
  store.commit('changeLoading', -1)
  console.log('error==', error)
  const { response } = error
  if (response) {
    const data = response.data
    Toast.fail(data.message)
  }
  return Promise.reject(error)
}
// 请求拦截器
instance.interceptors.request.use((config) => {
  const appParams = JSON.parse(localStorage.getItem('appParams'))
  config.headers = {
    ...config.headers,
    ...appParams
  }
  if (config.method === 'POST') {
    config.data = JSON.stringify(config.data)
  }
  if (config.loading) {
    store.commit('changeLoading', 1)
  }
  return config
}, errorHandler)

instance.interceptors.response.use((response) => {
  const { data } = response
  if (data && !data.success) {
    const { code } = data
    const resMessage = data.message
    const codeStr = code.toString()
    switch (code) {
      case 403:
        Toast.fail('拒绝访问')
        break
      case 500:
        Toast.fail('程序异常，请联系管理员')
        break
      case 404:
        Toast.fail('很抱歉，资源未找到!')
        break
      case 504:
        Toast.fail('网络超时')
        break
      case 400:
        Toast.fail(resMessage)
        break
      case 401:
        //  userLogout(data)
        Toast.fail('程序异常，请联系管理员')
        break
      default:
        if (codeStr.indexOf('85') > -1) {
          Toast.fail(resMessage)
        } else {
          Toast.fail(resMessage)
        }
        break
    }
  }
  store.commit('changeLoading', -1)
  return data
}, errorHandler)

// 封装请求参数
export const request = ({
  method = 'post',
  url,
  params = {},
  baseURL = config.VITE_API_BASE_URL,
  loading = true
}) => {
  const httpParam = {
    method,
    url,
    // params,
    baseURL,
    loading
  }
  if (method === 'post') {
    httpParam.data = params
  } else {
    httpParam.params = params
  }
  return instance(httpParam)
}
export default request
